﻿#include "csv.h"
#include <QTime>
#include <QDateTime>
#include <QDir>
#include <QFile>
#include <QFileInfo>
#include <QIODevice>

QFile csvFile;

#define DIR_EXCEL "XLS"


int  Currentline= 1;
QDateTime establishTime = QDateTime::currentDateTime();
//bool isOpened = false;
clock_t establishClock = clock();


QString FileName = "";
QString FileNameAndAppend = "";


void Csv::Rename(QString FileName_Append){
    if(FileName.length() < 1)return;
    QFile file(FileNameAndAppend);
    bool isOK = file.rename(FileName+FileName_Append + ".csv");
    if(isOK)
        return;
}





unsigned int Csv::Excel(void * pVoid){

    QDir dir;
    dir.mkdir(DIR_EXCEL);
    QDateTime dateTime = QDateTime::currentDateTime();
    establishTime = dateTime;
    FileName = "XLS/"+dateTime.addDays(0).toString("yyyy-MM-dd-hh-mm");
    QString Sheetpath = FileName + QString::fromLocal8Bit(".csv");
    FileNameAndAppend = Sheetpath;

    csvFile.setFileName(Sheetpath);
    QFileInfo ResultSheet(Sheetpath);

    if(ResultSheet.isFile()==false)//若不存在则新建
    {
        csvFile.open(QIODevice::ReadWrite|QIODevice::Append|QIODevice::Text);
        csvFile.write("序号,时间,丝径,张力\n");
        establishClock = clock();
        isOpened = true;
        Currentline= 1;
    }
    else
    {
        csvFile.open(QIODevice::ReadWrite|QIODevice::Text);
        Currentline= 1;
        while(!csvFile.atEnd()) {
            csvFile.readLine();
            Currentline++;
        }
        Currentline=Currentline-1;
        csvFile.close();
        if(csvFile.open(QIODevice::ReadWrite|QIODevice::Append|QIODevice::Text)){
            isOpened = true;
            std::cout <<"opened"<<std::endl;
            establishClock = clock();
        }else {
            isOpened = false;
            std::cout <<"openfailed" <<std::endl;
        }

    }

    return  isOpened;
     //   ::WaitForSingleObject(_global::GetIns()->evt_Csv.get(),INFINITE);
      //  const QByteArray WillSave = QByteArray(_global::GetIns()->WillWriteCsv.toStdString().data());
      //  csvFile.write(WillSave);
      //  _global::GetIns()->evt_Csv.ResetEvent();




}






void Csv::Write(QString Str){
    if(!isOpened) return;
    const QByteArray WillSave = Str.toUtf8();
    csvFile.write(WillSave);
    Currentline++;
    clock_t nc = clock();
    static clock_t oc = nc;
    if((nc - oc) > 500) csvFile.flush();
    oc = nc;
}

QString Csv::GetCurrentLine(){
    return QString::number(Currentline);
}

int Csv::CurrentLine(){
    return Currentline;
}

QDateTime Csv::InitTime(){
    return establishTime;
}

clock_t Csv::EstablishClock(){
    return establishClock;
}

void Csv::Init()
{

        if(!isOpened)
        Excel(nullptr);
}

void Csv::Close(){

    csvFile.close();
    isOpened = false;
}

Csv::Csv()
{
    //(HANDLE)_beginthreadex(NULL, 0, Excel, this, 0, NULL);
}
